package com.th.therp.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.th.therp.pojo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import static com.aliyun.teautil.Common.toJSONString;

/**
 * 阿里云短信工具类
 */
@Component
public class SmsUtils {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    private static String accessKeyId =  "LTAI5tRJNWn7LwGU9FthbHkt";
    private static String accessKeySecret = "UTrQ1zhcARKT5YpbZDr7DJYgvlcOyk";
    private static String endpoint = "dysmsapi.aliyuncs.com";
    private static String signName = "阿里云短信测试";
    private static String templateCode = "SMS_154950909";

    public void sendSms(String phone) throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID与AccessKey Secret
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 配置 Endpoint(短信服务器地址)
        config.endpoint = endpoint;
        String code = CodeUtils.getCode();
        //构造请求配置
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        // 初始化请求客户端
        Client client = new Client(config);
        // 获取响应对象
        System.out.println(code);
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        redisTemplate.opsForValue().set("code", String.valueOf(code),1, TimeUnit.MINUTES);
        // 响应包含服务端响应的 body 和 headers
        System.out.println(Result.success(toJSONString(sendSmsResponse)));
    }
}
